package com.easyoffer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyoffer.common.*;
import com.easyoffer.common.util.ResultUtils;
import com.easyoffer.constant.CommonConstant;
import com.easyoffer.constant.UserConstant;
import com.easyoffer.service.QuestionBankService;
import com.easyoffer.service.UserService;
import com.easyoffer.annotation.RoleCheck;
import com.easyoffer.exception.BusinessException;
import com.easyoffer.model.dto.questionbank.QuestionBankUpdateRequest;
import com.easyoffer.model.dto.questionbank.QuestionBankAddRequest;
import com.easyoffer.model.entity.QuestionBank;
import com.easyoffer.model.vo.QuestionBankVO;
import com.easyoffer.model.vo.UserVO;
import com.easyoffer.mapper.QuestionBankMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 何文斌
* @description 针对表【question_bank(题库)】的数据库操作Service实现
* @createDate 2025-03-15 21:09:28
*/
@Service
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankMapper, QuestionBank>
    implements QuestionBankService {

    @Autowired
    UserService userService;
    @Transactional
    @RoleCheck( mustRole = "admin")
    @Override
    public BaseResponse<QuestionBankVO> addQuestionBank(QuestionBankAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        String title = addRequest.getTitle();
        if (StringUtils.isBlank(title)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"题库标题为空");
        }
        UserVO loginUser = (UserVO) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        QuestionBank questionBank = new QuestionBank();
        BeanUtil.copyProperties(addRequest,questionBank);
        questionBank.setUserId(loginUser.getId());
        boolean save = this.save(questionBank);
        if (save){
            QuestionBankVO questionBankVO = new QuestionBankVO();
            BeanUtil.copyProperties(questionBank,questionBankVO);
            return ResultUtils.success(questionBankVO);
        }
        //添加失败
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }

    @RoleCheck( mustRole = "admin")
    @Override
    public BaseResponse<Boolean> updateQuestionBank(QuestionBankUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        Long id = updateRequest.getId();
        String title = updateRequest.getTitle();
        String description = updateRequest.getDescription();
        String picture = updateRequest.getPicture();
        Integer priority = updateRequest.getPriority();
        Integer viewNum = updateRequest.getViewNum();
        if (StringUtils.isAllBlank(title,description,picture) && priority == null && viewNum == null)
            return ResultUtils.success(true);
        QuestionBank questionBank = new QuestionBank();
        UserVO loginUser = (UserVO) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        questionBank.setId(id);
        questionBank.setUserId(loginUser.getId());
        if (StringUtils.isNotBlank(title))
            questionBank.setTitle(title);
        if (StringUtils.isNotBlank(description))
            questionBank.setDescription(description);
        if (StringUtils.isNotBlank(picture))
            questionBank.setPicture(picture);
        if (priority != null)
            questionBank.setPriority(priority);
        if (viewNum != null)
            questionBank.setViewNum(viewNum);
        if (this.updateById(questionBank)){
            return ResultUtils.success(true);
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }

    @RoleCheck( mustRole = "admin")
    @Override
    public BaseResponse<Boolean> deleteQuestionBank(DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        boolean deleted = this.removeById(deleteRequest.getId());
        if (deleted)
            return ResultUtils.success(true);
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }


    @Override
    public Page<QuestionBank> getQuestionBankPage(PageRequest pageRequest, HttpServletRequest request) {
        if (pageRequest == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        UserVO loginUser = (UserVO) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        if (pageRequest.getCurrent() == 0)
            pageRequest.setCurrent(1);
        //非管理员每次只能查20条
        if (pageRequest.getPageSize() <= 0 || ( !userService.isAdmin(request) && pageRequest.getPageSize() > 20) )
            pageRequest.setPageSize(20);
        Page<QuestionBank> page = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
        // 根据排序字段和正序倒序设置排序规则
        String sortField = pageRequest.getSortField();
        String sortOrder = pageRequest.getSortOrder();
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(sortField)){
            OrderItem orderItem = new OrderItem();
            if (StringUtils.isBlank(sortOrder))
                sortOrder = CommonConstant.SORT_ORDER_ASC;
            orderItem.setColumn(sortField);
            orderItem.setAsc(sortOrder.equals(CommonConstant.SORT_ORDER_ASC));
            queryWrapper.orderBy(true,orderItem.isAsc(),orderItem.getColumn());
        }
        return this.page(page,queryWrapper);
    }

    @Override
    public Page<QuestionBankVO> listQuestionBankPageVO(PageRequest pageRequest, HttpServletRequest request) {
        if (pageRequest == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        int current = pageRequest.getCurrent();
        int pageSize = pageRequest.getPageSize();
        String sortField = pageRequest.getSortField();
        String sortOrder = pageRequest.getSortOrder();
        Page<QuestionBank> page = new Page<>(current,pageSize);
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(sortField)){
            if (StringUtils.isBlank(sortOrder))
                sortOrder = CommonConstant.SORT_ORDER_ASC;
            queryWrapper.orderBy(true,sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        }
        Page<QuestionBank> questionBankPage  = this.page(page, queryWrapper);
        Page<QuestionBankVO> questionBankVOPage = new Page<>(questionBankPage.getCurrent(),questionBankPage.getSize(),questionBankPage.getTotal());
        if (questionBankPage.getRecords().size() == 0){
            questionBankVOPage.setRecords(new ArrayList<>());
            return questionBankVOPage;
        }
        List<QuestionBankVO> questionVOList = questionBankPage.getRecords()
                .stream().map(QuestionBankVO::objToVo)
                .collect(Collectors.toList());
        questionBankVOPage.setRecords(questionVOList);
        return questionBankVOPage;
    }

}




